Grouping¶

group_by_first_letter.py¶

NOTES

  • groups[key] = []: here we initialize a group with an empty list
    • draw out an example dictionary: each key pointing to a separate list
  • groups[key].append(word): here we append the word to the list in groups[key]
    • on the diagram, show how when the next word comes up, it gets assigned to one of those lists
  • key = word[0]: here we decide what the things in a group have in common
    • e.g. in this case, we are using the first letter of the word.
  • step through with debugger.

🖌 Grouping Pattern¶

  1. Define the key
  • For a given item, what group does it belong in?
  • Often you will use a separate function for this
  1. Initialize the key (if necessary)
  • If the key hasn't been seen before, setup a new group for it
  • i.e. if key not in groups, then initialize the key, often to an empty list
  1. Add the item to the group
  • e.g. append the item to the list for the respective group

👩🏾‍🎨 Group by size¶

Group a sequence of words by their length.

Use an input loop. Print word groups at the end.

group_by_size.py¶

🎨 tuple + dict¶

In [1]:
data = {
    ('Monday', '1pm'): 'CS 110',
    ('Tuesday', '2pm'): 'CS 235',
    ('Wednesday', '1pm'): 'CS 110',
    ('Thursday', '2pm'): 'CS 235',
    ('Friday', '1pm'): 'CS 110'
}
In [2]:
data['Monday']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[2], line 1
----> 1 data['Monday']

KeyError: 'Monday'
In [3]:
data['Monday', '1pm']
Out[3]:
'CS 110'

You can use a tuple as a key in a dictionary.

In [4]:
time = ['Monday', '1pm']
data[time]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[4], line 2
      1 time = ['Monday', '1pm']
----> 2 data[time]

TypeError: unhashable type: 'list'

You can't use a list or a dict as a key in a dictionary.

If you see an "unhashable type" TypeError, it's because you are trying to use something as a key that doesn't work as a key (list and dict are the more common offenders).

You'll learn what "unhashable" means in CS 235. 🙂

👨🏻‍🎨 First and Last¶

Group words based on their first and last letters.

Use an input loop. Print the groups at the end.

first_and_last.py¶

👩🏻‍🎨 Vowelly¶

Group words by the number of vowels.

Input loop. Specify prompt from commandline.

vowelly.py¶

🖌 Grouping Pattern¶

  1. Define the key
  • For a given item, what group does it belong in?
  • Often you will use a separate function for this
  1. Initialize the key (if necessary)
  • If the key hasn't been seen before, setup a new group for it
  • i.e. if key not in groups, then initialize the key, often to an empty list
  1. Add the item to the group
  • e.g. append the item to the list for the respective group